﻿using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApplication1.Data;
using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;

namespace WebApplication1.Services
{
    public class JwtTokenVerificationService
    {
        public async Task<TokenModel> GenerateTokenAsync(UserModel userModel)
        {
            if (InData.userList.Where(x => x.UserName == userModel.UserName && x.PassWord == userModel.PassWord).Any())
            {
                //创建令牌用到的信息
                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub,"admin@admin.com"),
                    new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName,userModel.UserName)
                };
                //加密的键
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234566543211234"));
                //加密方式
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                //创建token
                var token = new JwtSecurityToken("localhost", "localhost", claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds);
                return new TokenModel
                {
                    TokenString = new JwtSecurityTokenHandler().WriteToken(token),
                    Refreshtime = DateTime.UtcNow.AddMinutes(30),
                    Success = true
                };
            }
            return new TokenModel
            {

                Success = false
            };
        }
    }
    public class TokenModel
    {
        public string TokenString { get; set; }
        public DateTime Refreshtime { get; set; }
        public bool Success { get; set; }
    }
    public class UserModel
    {
        public string UserName { get; set; }

        public string PassWord { get; set; }
    }
}
